import React, { useState } from 'react';
import { AutoComplete, Button, Card, Space, Result, Spin } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import axios from 'axios';

const stockOptions = [
  { value: '000001', label: '000001 - 平安银行' },
  { value: '000002', label: '000002 - 万科A' },
  { value: '600519', label: '600519 - 贵州茅台' },
  { value: '002594', label: '002594 - 比亚迪' },
  { value: '300750', label: '300750 - 宁德时代' },
  { value: '00700', label: '00700 - 腾讯控股' },
  { value: '03690', label: '03690 - 美团' },
  { value: '09988', label: '09988 - 阿里巴巴' },
  { value: '02333', label: '02333 - 长城汽车' },
  { value: '01810', label: '01810 - 小米集团' },
];

const StockSearch = () => {
  const [stockInput, setStockInput] = useState('');
  const [analysisResult, setAnalysisResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleSearch = async () => {
    if (!stockInput.trim()) {
      return;
    }

    setLoading(true);
    try {
      // iFlow分析API调用
      const response = await axios.post('http://localhost:5001/api/analyze', {
        stockCode: stockInput,
      });
      setAnalysisResult(response.data);
    } catch (error) {
      console.error('分析失败:', error);
      setAnalysisResult({
        error: true,
        message: '分析失败，请稍后重试',
      });
    } finally {
      setLoading(false);
    }
  };

  const onSelect = (value) => {
    setStockInput(value);
  };

  const onSearch = (value) => {
    setStockInput(value);
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Card title="股票分析" style={{ marginBottom: 24 }}>
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <AutoComplete
            style={{ width: '100%' }}
            options={stockOptions}
            onSelect={onSelect}
            onSearch={onSearch}
            placeholder="请输入股票代码或名称（如：000001 平安银行）"
            value={stockInput}
            onChange={setStockInput}
            allowClear
            filterOption={(inputValue, option) =>
              option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1 ||
              option.label.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
            }
          />
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
            loading={loading}
            disabled={!stockInput.trim()}
          >
            使用iFlow分析
          </Button>
        </Space>
      </Card>

      {analysisResult && !loading && (
        <Card title="分析结果">
          {analysisResult.error ? (
            <Result
              status="error"
              title="分析失败"
              subTitle={analysisResult.message}
            />
          ) : (
            <div>
              <h3>股票：{analysisResult.stockCode}</h3>
              <p>分析结论：{analysisResult.conclusion}</p>
              <p>风险等级：{analysisResult.riskLevel}</p>
              <p>目标价格：{analysisResult.targetPrice}</p>
              <p>建议：{analysisResult.recommendation}</p>
            </div>
          )}
        </Card>
      )}
    </div>
  );
};

export default StockSearch;